import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class DialogUtil {
  static Future showElasticDialog({
    BuildContext? context,
    bool barrierDismissible = true,
    required WidgetBuilder builder,
  }) {
    context ??= Get.context!;
    final ThemeData? theme = Theme.of(context);
    return showGeneralDialog(
      context: context,
      pageBuilder: (BuildContext buildContext, Animation<double> animation, Animation<double> secondaryAnimation) {
        final Widget pageChild = Builder(builder: builder);
        return SafeArea(
          child: Builder(builder: (BuildContext context) {
            // 这里使用Wrap，是因为如果不使用的话，默认高度是占满全屏
            // center是用于居中，否则就从左上角开始显示
            return theme != null ? Theme(data: theme, child: Center(child: Wrap(children: [pageChild]))) : Center(child: Wrap(children: [pageChild]));
          }),
        );
      },
      barrierDismissible: barrierDismissible,
      barrierLabel: MaterialLocalizations.of(context).modalBarrierDismissLabel,
      barrierColor: Colors.black54,
      transitionDuration: const Duration(milliseconds: 550),
      transitionBuilder: _buildDialogTransitions,
    );
  }

  static Widget _buildDialogTransitions(BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
    return FadeTransition(
      opacity: CurvedAnimation(
        parent: animation,
        curve: Curves.easeOut,
      ),
      child: SlideTransition(
        position: Tween<Offset>(begin: const Offset(0.0, 0.3), end: Offset.zero).animate(CurvedAnimation(
          parent: animation,
          curve: animation.status != AnimationStatus.forward ? Curves.easeOutBack : ElasticOutCurve(0.85),
        )),
        child: child,
      ),
    );
  }
}
